package client_package;

import java.io.IOException;

import javax.swing.JOptionPane;

import client_package.Controleur.StatutSound;

public class ThreadAttenteConnection implements Runnable {
	private Controleur c;
	
	public ThreadAttenteConnection(Controleur c) {
		this.c = c;
	}

	public void run() {
		//System.out.println("J'ouvre threadAttenteConnec\n");
		String ch = "";
		String loginOppose=c.getLogin();
		int choix;
		boolean quitter=false;
		try {
			ch = c.getIn_son().readLine();
			if (!ch.equals("exit"))
			{
				while(!quitter)
				{
					choix = JOptionPane.showConfirmDialog(null, "Acceptez-vous la conversation de " + ch, "Demande de conversation", JOptionPane.YES_NO_OPTION);
					loginOppose = ch;
					c.getOut_Confirm().println((choix == JOptionPane.YES_OPTION ? "OK" : "NO"));
					c.getOut_Confirm().flush();
					if (choix == JOptionPane.YES_OPTION)
					{
						c.getOut_Son().println("exit");
						c.getOut_Son().flush();
						quitter=true;
						c.setStatutSound(StatutSound.Ecoute);
					}
					else
					{
						loginOppose = c.getLogin();
						ch = c.getIn_son().readLine();
						if (ch.equals("exit"))
						{
							quitter=true;
						}
					}				
				}
			}
			
			if(!loginOppose.equals(c.getLogin()))
			{
				c.getOut().println("com");
				c.getOut().flush();
				c.getOut().println(loginOppose);
				c.getOut().flush();
				c.getTInfos().interrupt();
				String info = c.getIn().readLine();
				if(info != null) {
					if(info.equals("Com : OK")) {		
						c.getVue().setVisible(false);
						c.setVues(new VueConversation(c, loginOppose));
						c.getVue().setVisible(true);
						c.setTListener();
						c.getTListener().start();
						c.setTListenerSound();
						c.getTListenerSound().start();
						c.setTRecevoirLaMain();
						c.getTRecevoirLaMain().start();
					}
				}
			}
		} catch (IOException e1) {
		
			e1.printStackTrace();
		}
		//System.out.println("Je sors threadAttenteConnec\n");
	}
}